package com.tping.lock.actual;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 报警服务
 */
public class AlarmAgent {

    /**
     * 初始化 报价服务
     * 1、连接报警服务器的线程就连接
     * 2、定时调度线程去每隔5s检查一次连接
     */
    public void init(){
        // 报警服务与报警服务器的连接线程
        Thread connectingThread = new Thread(new ConnectingTask());
        connectingThread.start();

        // 每隔5s发送一次心跳到报警服务器
        ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(5, new ThreadFactory() {

            private AtomicInteger index = new AtomicInteger();

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread();
                // 设置线程名称
                thread.setName("heartbeat-thread-" + index);
                // 当JVM退出时退出
                thread.setDaemon(true);
                return thread;
            }
        });

        // 定时器，每隔5s执行一次
        threadPoolExecutor.scheduleAtFixedRate(new HeartbeatTask(), 5000, 2000, TimeUnit.MILLISECONDS);
    }


    /**
     * 与报警服务器建立连接的线程
     */
    class ConnectingTask implements Runnable {

        @Override
        public void run() {

            System.out.println("alarm connected");
            onConnected();
        }
    }

    public void onConnected() {
    }

    /**
     *
     */
    class HeartbeatTask implements Runnable {
        @Override
        public void run() {

        }
    }
}
